package com.lishe.lishe.lishe.module.excitation.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerViewRefreshListener;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshRecyclerView;
import com.lishe.lishe.lishe.bean.SpaceItemDecoration;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.http.HttpUser;
import com.lishe.lishe.lishe.module.excitation.activity.PersonGiftActivity;
import com.lishe.lishe.lishe.module.excitation.adapter.PersonGiftListAdapter;
import com.lishe.lishe.lishe.module.excitation.adapter.PersonSendGiftAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.MineExcitationObject;
import com.lishe.lishe.lishe.module.excitation.bean.UserIntegralObject;
import com.lishe.lishe.lishe.module.excitation.http.HttpExcitation;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnMessageChangeListener;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnPersonGiftCostListener;
import com.lishe.lishe.lishe.module.excitation.presenter.MinePresenter;
import com.lishe.lishe.lishe.module.recharge.activity.RechargeIntegralActivity;
import com.lishe.lishe.lishe.utils.BitmapUtils;
import com.lishe.lishe.lishe.utils.FileUtils;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.utils.StringUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.retrofit.BaseDataPageBody;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.smarttop.library.utils.LogUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

/**
 * Created by DELL on 2017/10/30.
 */

public class ShowSendGiftDialog extends Dialog {


    public ShowSendGiftDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
    }

    public static class Builder implements View.OnClickListener {
        private Activity context;
        private ShowSendGiftDialog dialog;
        private PersonSendGiftAdapter adapter;
        private List<MineExcitationObject> list;
        private String giftIds;
        private String eventUserId;//接收人id
        private String eventId;//事件id
        private int pointsType;//积分类型：1：通用积分（目前只支持通用积分）
        private int remainScore = -1;//客户可用积分
        private OnMessageChangeListener listener;

        private RecyclerView mRecyclerView;
        private SmartRefreshLayout mSmartRefreshLayout;
        private TextView num;
        ImageView dissmiss;
        TextView giftNotEnough;
        TextView commit;

        public Builder(Activity context) {
            this.context = context;
        }

        /**
         * 设置接收人id
         *
         * @param eventUserId
         * @return
         */
        public Builder setEventUserId(String eventUserId) {
            this.eventUserId = eventUserId;
            return this;
        }

        /**
         * 设置事件id
         *
         * @param eventId
         * @return
         */
        public Builder setEventId(String eventId) {
            this.eventId = eventId;
            return this;
        }

        /**
         * 设置积分类型，积分类型：1：通用积分（目前只支持通用积分）
         *
         * @param pointsType
         * @return
         */
        public Builder setPointsType(int pointsType) {
            this.pointsType = pointsType;
            return this;
        }

        /**
         * 设置回调提醒
         *
         * @param listener
         * @return
         */
        public Builder setOnMessageChangeListener(OnMessageChangeListener listener) {
            this.listener = listener;
            return this;
        }

        public ShowSendGiftDialog create() throws NullPointerException {
            if (dialog == null) {
                dialog = new ShowSendGiftDialog(context, R.style.MyDialog);
                View contentView = context.getLayoutInflater().inflate(R.layout.dialog_send_gift, null);
//                contentView.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        dialog.dismiss();
//                    }
//                });

                initView(contentView);
                initAdapter();
                setListener();
                //设置刷新控件
                setSmartRefreshLayout();

                getIntegral();


                dialog.setContentView(contentView);
                dialog.getWindow().setGravity(Gravity.BOTTOM);
                dialog.setCanceledOnTouchOutside(true);
                dialog.setCancelable(true);
                WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.MATCH_PARENT;
                dialog.getWindow().setAttributes(lp);
            }
            return dialog;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dissmiss:
                    dissmiss();
                    break;
                case R.id.gift_not_enough:
                    if (remainScore == -1) {//请求用户积分失败
                        getIntegral();
                    } else {//积分不足,跳转到积分充值
                        RechargeIntegralActivity.jump(context);
                    }
                    break;
                case R.id.commit:
                    if (remainScore == -1 || giftNotEnough.getVisibility() == View.VISIBLE) {
                        toast(context.getString(R.string.money_not_enought_please_recharge));
                    } else {
                        if (!TextUtils.isEmpty(giftIds)) {
                            sendGift();
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                        }
                    }
                    break;
            }
        }

        public void show() {
            try {
                create();
                if(dialog!=null&&!dialog.isShowing()){
                    dialog.show();
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

        public void dissmiss() {
            if (dialog != null) {
                dialog.dismiss();
                dialog.cancel();
            }
            if (adapter != null) {
                adapter.unRegisterOnPersonGiftCostListener();
            }
            if (listener != null) {
                listener = null;
            }
        }

        private void setListener() {
            dissmiss.setOnClickListener(this);
            commit.setOnClickListener(this);
            giftNotEnough.setOnClickListener(this);
        }

        private void initAdapter() {
            list = new ArrayList<>();
            adapter = new PersonSendGiftAdapter(context, this.list,BitmapUtils.getDisplayWidth(context));
            adapter.registerOnPersonGiftCostListener(new OnPersonGiftCostListener() {
                @Override
                public void calculateGiftCost(double giftCost, String giftIds, Map<String, MineExcitationObject> exchangeGifts) {
                    if (remainScore == -1) {
                        if (giftNotEnough.getVisibility() == View.GONE) {
                            giftNotEnough.setVisibility(View.VISIBLE);
                            giftNotEnough.setText("点击重新获取");
                        }
                    } else {
                        if (remainScore < giftCost) {
                            giftNotEnough.setVisibility(View.VISIBLE);
                            giftNotEnough.setText("余额不足去充值>");
                        } else {
                            giftNotEnough.setVisibility(View.GONE);
                        }
                    }
                    Builder.this.giftIds = giftIds;
                }

            });
            mRecyclerView.setAdapter(adapter);
        }

        private void initView(View contentView) {
            dissmiss = contentView.findViewById(R.id.dissmiss);
            num = contentView.findViewById(R.id.num);
            giftNotEnough = contentView.findViewById(R.id.gift_not_enough);
            giftNotEnough.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            commit = contentView.findViewById(R.id.commit);
            mSmartRefreshLayout = contentView.findViewById(R.id.refreshlayout);

            mRecyclerView = contentView.findViewById(R.id.list);
            mRecyclerView.setLayoutManager(new GridLayoutManager(context, 3));
            mRecyclerView.addItemDecoration(new SpaceItemDecoration(0, Utils.dip2px(context, 10), Utils.dip2px(context, 10), Utils.dip2px(context, 10)));

//            num.setText(String.valueOf(remainScore));
        }

        private void setSmartRefreshLayout() {
            mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
            mSmartRefreshLayout.setEnableLoadmore(false);//关闭上拉加载功能

            mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    getGift();
                }
            });

            mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
                @Override
                public void onLoadmore(RefreshLayout refreshlayout) {
                    getGift();
                }
            });
        }

//        /**
//         * 小礼数量-1，当小礼数量为0时，移除小礼
//         */
//        private void removeGiftWithExchangeGift() {
//            MineExcitationObject mine = null;
//            for (MineExcitationObject object : list) {
//                if (object.getGiftId().equals(giftIds)) {
//                    mine = object;
//                }
//            }
//            list.remove(mine);
//            adapter.notifyDataSetChanged();
//        }

        private void sendGift() {
            try {
                MinePresenter.getInstance().sendGift(Globals.getToken(), eventUserId, giftIds, eventId, String.valueOf(pointsType), new DataResponseListener() {
                    @Override
                    public void onSuccess(Object dataResponse) {
                        toast("赠送成功");
                        listener.messageChange(OnMessageChangeListener.GIFT_CHANGE_SUCCESS, 1);
//                            getIntegral();
                        dissmiss();
                    }

                    @Override
                    public void onFail(String failMessage) {
                        toast(failMessage);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        toast(context.getString(R.string.network_or_server_exception));
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                toast(context.getString(R.string.data_parse_fail));
            }
        }

        /**
         * 获取用户积分
         */
        private void getIntegral() {
            try {
                MinePresenter.getInstance().getUserIntegral(Globals.getToken(), new DataResponseListener<UserIntegralObject>() {
                    @Override
                    public void onSuccess(UserIntegralObject dataResponse) {
                        remainScore = dataResponse.getBalance();
                        num.setText(String.valueOf(remainScore));
                        giftNotEnough.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFail(String failMessage) {
                        toast(failMessage);
                        toast("获取用户积分失败");
                        giftNotEnough.setVisibility(View.VISIBLE);
                        giftNotEnough.setText("点击重新获取");
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        toast(context.getString(R.string.network_or_server_exception));
                        giftNotEnough.setVisibility(View.VISIBLE);
                        giftNotEnough.setText("点击重新获取");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                toast(context.getString(R.string.data_parse_fail));
            }
        }

        /**
         * 获取个人小礼列表
         */
        public void getGift() {
            try {
                MinePresenter.getInstance().searchEncourageGifts(Globals.getToken(), new DataResponseListener<List<MineExcitationObject>>() {
                    @Override
                    public void onSuccess(List<MineExcitationObject> dataResponse) {
                        mSmartRefreshLayout.finishRefresh(500, true);
                        if (dataResponse != null) {
                            list.clear();
                            list.addAll(dataResponse);
                            adapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFail(String failMessage) {
                        mSmartRefreshLayout.finishRefresh(500, true);
                        toast(failMessage);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mSmartRefreshLayout.finishRefresh(500, true);
                        toast(context.getString(R.string.network_or_server_exception));
                    }
                });
            } catch (Exception e) {
                mSmartRefreshLayout.finishRefresh(500, true);
                e.printStackTrace();
                toast(context.getString(R.string.data_parse_fail));
            }
        }

        private void toast(String message) {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        }

    }

}
